from google.appengine.ext import db
import random

class UserCounterShard(db.Model):    
    count = db.IntegerProperty(required=True, default=0)
      
class PostCounterShard(db.Model):
    count=db.IntegerProperty(required=True, default=0)
    
class Counter:
    NUM_SHARDS = 5
    Shard=None
    @staticmethod
    def get_count():
        """Retrieve the value for a given sharded counter."""
        total = 0
        for counter in Counter.Shard.all():
            total += counter.count
        
        return total

    @staticmethod
    def inc_and_get():
        Counter.increment()
        return Counter.get_count()
                
    @staticmethod
    def increment():
        """Increment the value for a given sharded counter."""
        def txn():
            index = random.randint(0, Counter.NUM_SHARDS - 1)
            shard_name = "shard" + str(index)
            counter = Counter.Shard.get_by_key_name(shard_name)
            if counter is None:
                counter = Counter.Shard(key_name=shard_name)
            counter.count += 1
            counter.put()
            #print "shard:%s,count %s"%(shard_name,counter.count)
            #return counter.count
        db.run_in_transaction(txn)
            




    
class UserCounter(Counter):
    Counter.NUM_SHARDS  =5
    Counter.Shard       =UserCounterShard
class PostCounter(Counter):
    Counter.NUM_SHARDS  =20
    Counter.Shard       =PostCounterShard
    
def get_uid():
    return Counter.inc_and_get()   
  

def main():
    
    print UserCounter.inc_and_get()

if __name__ == '__main__':
    main()       